<template>
  <div class="ai-assistant" v-if="shouldShow">
    <transition name="fade">
      <div class="chat-window" v-if="isChatOpen">
        <div class="chat-header">
          <span>智能助手</span>
          <div class="header-buttons">
            <button @click="toggleHistory" class="history-btn" title="历史记录">
              📋
            </button>
            <button @click="toggleChat" class="close-btn">&times;</button>
          </div>
        </div>
        <div class="chat-body" ref="chatBody">
          <div v-for="(message, index) in messages" :key="index" :class="['chat-message', message.sender]">
            <div class="message-content" v-if="message.type === 'text'">{{ message.text }}</div>
            <div v-else-if="message.type === 'products'">
              <div v-for="product in message.products" :key="product.id" class="product-card">
                <div>{{ product.name }}</div>
                <div>￥{{ product.price }}</div>
                <a :href="product.link">查看详情</a>
              </div>
            </div>
          </div>
        </div>
        <div class="chat-footer">
          <input v-model="userInput" @keyup.enter="sendMessage" placeholder="输入您的问题..." />
          <button @click="sendMessage">发送</button>
        </div>
      </div>
    </transition>

    <!-- 历史记录窗口 -->
    <transition name="fade">
      <div class="history-window" v-if="isHistoryOpen">
        <div class="history-header">
          <span>聊天历史记录</span>
          <button @click="toggleHistory" class="close-btn">&times;</button>
        </div>
        <div class="history-body" ref="historyBody">
          <div v-if="loading" class="loading">加载中...</div>
          <div v-else-if="historyRecords.length === 0" class="no-history">暂无历史记录</div>
          <div v-else class="history-list">
            <div v-for="(record, index) in historyRecords" :key="index" class="history-item">
              <div class="history-question" @click="resendQuestion(record.question, record.answer, record.type, record.data)" title="点击查看此对话">
                <strong>用户:</strong> {{ record.question }}
              </div>
              <div class="history-answer">
                <strong>AI:</strong> {{ record.answer }}
              </div>
              <div class="history-time">{{ record.time }}</div>
            </div>
          </div>
        </div>
      </div>
    </transition>

    <button class="chat-toggle-btn" @click="toggleChat">
      <span class="chat-toggle-text">AI</span>
    </button>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, nextTick, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import api from '@/network/api'

interface Message {
  text?: string
  sender: 'user' | 'bot'
  type: 'text' | 'products'
  products?: any[]
}

interface HistoryRecord {
  question: string
  answer: string
  time: string
  type?: string
  data?: string
}

export default defineComponent({
  name: 'AiAssistant',
  setup() {
    const route = useRoute()
    const isChatOpen = ref(false)
    const isHistoryOpen = ref(false)
    const userInput = ref('')
    const messages = ref<Message[]>([
      { text: '您好！我是您的智能助手，有什么可以帮助您的吗？', sender: 'bot', type: 'text' }
    ])
    const chatBody = ref<HTMLDivElement | null>(null)
    const historyBody = ref<HTMLDivElement | null>(null)
    const historyRecords = ref<HistoryRecord[]>([])
    const loading = ref(false)

    // 计算属性：判断是否应该显示AI助手
    const shouldShow = computed(() => {
      const currentName = route.name;
      // 只在首页、商店、视频、购物车、我的五个界面显示
      const showNames = ['home', 'store', 'video', 'cart', 'profile'];
      return showNames.includes(currentName as string);
    })

    const toggleChat = () => {
      isChatOpen.value = !isChatOpen.value
      if (isHistoryOpen.value) {
        isHistoryOpen.value = false
      }
    }

    const toggleHistory = async () => {
      isHistoryOpen.value = !isHistoryOpen.value
      if (isChatOpen.value) {
        isChatOpen.value = false
      }
      
      if (isHistoryOpen.value) {
        await loadHistoryRecords()
      }
    }

    const loadHistoryRecords = async () => {
      loading.value = true
      try {
        const response: any = await api.getAIHistory()
        if (response.code === 100 && response.data) {
          historyRecords.value = response.data.records || []
        } else {
          historyRecords.value = []
        }
      } catch (error) {
        console.error('加载历史记录失败:', error)
        historyRecords.value = []
      } finally {
        loading.value = false
      }
    }

    const scrollToBottom = () => {
      nextTick(() => {
        if (chatBody.value) {
          chatBody.value.scrollTop = chatBody.value.scrollHeight
        }
      })
    }

    const sendMessage = async () => {
      const text = userInput.value.trim()
      if (!text) return

      messages.value.push({ text, sender: 'user', type: 'text' })
      userInput.value = ''
      scrollToBottom()

      // 调用后端API
      try {
        const res: any = await api.askAI(text)

        if (res && res.code === 100) {
          // 直接使用res.data作为返回的结果
          const result = res.data
          
          if (typeof result === 'string') {
            // 如果返回的是字符串，直接显示为文本消息
            messages.value.push({
              text: result,
              sender: 'bot',
              type: 'text'
            })
          } else if (result && result.type === 'products') {
            // 如果返回的对象包含type字段为products
            messages.value.push({
              sender: 'bot',
              type: 'products',
              products: result.products
            })
          } else if (result && result.answer) {
            // 如果返回的对象包含answer字段
            messages.value.push({
              text: result.answer,
              sender: 'bot',
              type: 'text'
            })
          } else {
            // 其他情况，尝试将整个结果转为字符串显示
            messages.value.push({
              text: typeof result === 'object' ? JSON.stringify(result) : String(result),
              sender: 'bot',
              type: 'text'
            })
          }
        } else {
          messages.value.push({
            text: `API响应似乎不正确: ${res ? res.message : '无有效响应'}`,
            sender: 'bot',
            type: 'text'
          })
        }
      } catch (e: any) {
        let errorText = '抱歉，服务请求失败。';
        if (typeof e === 'string') {
          errorText = `请求出错: ${e}`;
        } else if (e && e.message) {
          errorText = `请求出错: ${e.message}`;
        } else {
          try {
            errorText = `请求出错: ${JSON.stringify(e)}`;
          } catch (stringifyError) {
            errorText = '请求失败，且错误详情无法展示。';
          }
        }
        messages.value.push({
          text: errorText,
          sender: 'bot',
          type: 'text'
        });
      }
      scrollToBottom()
    }

    const resendQuestion = async (question: string, answer: string, type: string = 'text', data?: string) => {
      // 关闭历史记录窗口，打开聊天窗口
      isHistoryOpen.value = false
      isChatOpen.value = true
      
      // 清空当前消息
      messages.value = [
        { text: '您好！我是您的智能助手，有什么可以帮助您的吗？', sender: 'bot', type: 'text' }
      ]
      
      // 添加历史记录中的问题
      messages.value.push({ text: question, sender: 'user', type: 'text' })
      
      // 根据类型添加不同的回答
      if (type === 'products' && data) {
        try {
          // 尝试解析商品数据
          const productsData = JSON.parse(data);
          messages.value.push({
            sender: 'bot',
            type: 'products',
            products: productsData
          });
        } catch (e) {
          // 如果解析失败，显示文本
          messages.value.push({ text: answer, sender: 'bot', type: 'text' });
        }
      } else {
        messages.value.push({ text: answer, sender: 'bot', type: 'text' });
      }
      
      // 滚动到底部
      await nextTick()
      scrollToBottom()
    }

    return {
      isChatOpen,
      isHistoryOpen,
      userInput,
      messages,
      chatBody,
      historyBody,
      historyRecords,
      loading,
      shouldShow,
      toggleChat,
      toggleHistory,
      sendMessage,
      resendQuestion
    }
  }
})
</script>

<style scoped>
.ai-assistant {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease, transform 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(10px);
}

.chat-toggle-btn {
  background-color: #3490dc;
  color: white;
  border: none;
  border-radius: 50%;
  width: 56px;
  height: 56px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  transition: transform 0.2s;
  font-size: 22px;
  font-weight: bold;
  position: relative;
}

.chat-toggle-btn:hover {
  transform: scale(1.08);
}

.chat-toggle-text {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  font-size: 22px;
  font-weight: bold;
  letter-spacing: 2px;
  color: #fff;
  user-select: none;
}

.chat-window,
.history-window {
  width: 90vw;
  max-width: 370px;
  height: 70vh;
  max-height: 600px;
  background: white;
  border-radius: 16px 16px 10px 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: absolute;
  bottom: 70px;
  right: 0;
}

@media (max-width: 600px) {
  .chat-window,
  .history-window {
    width: 96vw;
    height: 80vh;
    max-width: none;
    max-height: none;
    left: 2vw;
    right: 2vw;
    bottom: 80px;
    position: fixed;
    margin: 0 auto;
    border-radius: 18px 18px 12px 12px;
  }
  .ai-assistant {
    right: 16px;
    bottom: 70px;
  }
  .chat-toggle-btn {
    width: 42px;
    height: 42px;
    font-size: 16px;
  }
  .chat-toggle-text {
    font-size: 16px;
  }
}

.chat-header,
.history-header {
  padding: 15px;
  background: #3490dc;
  color: white;
  font-weight: bold;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  gap: 10px;
  align-items: center;
}

.history-btn {
  background: none;
  border: none;
  color: white;
  font-size: 18px;
  cursor: pointer;
  padding: 5px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.history-btn:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.close-btn {
  background: none;
  border: none;
  color: white;
  font-size: 24px;
  cursor: pointer;
}

.chat-body,
.history-body {
  flex-grow: 1;
  padding: 15px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.loading {
  text-align: center;
  color: #666;
  padding: 20px;
}

.no-history {
  text-align: center;
  color: #999;
  padding: 40px 20px;
  font-style: italic;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.history-item {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 12px;
  background-color: #f9f9f9;
}

.history-question {
  margin-bottom: 8px;
  color: #333;
  cursor: pointer;
  padding: 8px;
  border-radius: 6px;
  transition: background-color 0.2s;
  border: 1px solid transparent;
}

.history-question:hover {
  background-color: #e3f2fd;
  border-color: #2196f3;
  color: #1976d2;
}

.history-answer {
  margin-bottom: 8px;
  color: #666;
  white-space: pre-wrap;
}

.history-time {
  font-size: 12px;
  color: #999;
  text-align: right;
}

.chat-message .message-content {
  padding: 10px 15px;
  border-radius: 18px;
  max-width: 80%;
  word-wrap: break-word;
}

.chat-message.user {
  align-self: flex-end;
}

.chat-message.user .message-content {
  background-color: #3490dc;
  color: white;
  border-bottom-right-radius: 4px;
}

.chat-message.bot {
  align-self: flex-start;
}

.chat-message.bot .message-content {
  background-color: #f1f1f1;
  color: #333;
  border-bottom-left-radius: 4px;
}

.chat-footer {
  padding: 15px;
  border-top: 1px solid #eee;
  display: flex;
}

.chat-footer input {
  flex-grow: 1;
  border: 1px solid #ddd;
  padding: 10px;
  border-radius: 20px;
  margin-right: 10px;
  outline: none;
}

.chat-footer button {
  background-color: #3490dc;
  color: white;
  border: none;
  border-radius: 20px;
  padding: 10px 20px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.chat-footer button:hover {
  background-color: #0056b3;
}

.product-card {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 8px;
  margin: 8px 0;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.product-card img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  margin-bottom: 4px;
}
</style> 